package cn.anzhiyublog.staranimegallery.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 全局跨域配置
 *
 * @author 安知一只鱼
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "cross-origin-config")
public class GlobalCrossOriginConfig implements WebMvcConfigurer { // 实现 WebMvcConfigurer
    /**
     * 允许发送Cookie和认证信息
     */
    private boolean allowCredentials;

    /**
     * 放行域名
     */
    private String[] origins;

    /**
     * 放行方法
     */
    private String[] methods;

    /**
     * 放行请求头
     */
    private String[] headers;

    /**
     * 暴露响应头
     */
    private String[] exposedHeaders;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(allowCredentials)
//                .allowedOriginPatterns("*") // 如果需全放行就用pattern, 否则 * 和 allowCredentials 会冲突）
                .allowedOrigins(origins)
                .allowedMethods(methods)
                .allowedHeaders(headers)
                .exposedHeaders(exposedHeaders);
    }
}
